import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { JsonApiService } from "app/core/api/json-api.service";
import {config} from '../../shared/smartadmin.config';
import { NotificationService } from "../../shared/utils/notification.service";

declare var $: any;
declare var AMap: any;
declare var toAMapPoint: any;
declare var AMapToWgs4: any;
declare var toAMapPointArr: any;
@Component({
	selector: 'sa-path-fix',
	templateUrl: './path-fix2.component.html',
	styleUrls:['./path-fix2.css']
})
export class PathFix2Component implements OnInit {
	htmlParams={
		carNumber:'',
		deviceId:'',
		startTime:'',
		endTime:'',
		runTime:'',
		runBefore:'',
		stopTime:'',
		stopBefore:'',
		isMakeup:false,
		isRemove:false,
		isAutoApproach:true,
	}
	planningMarker:any={
		starPoint:{
			val:'',
			marker:undefined,
		},
		endPoint:{
			val:'',
			marker:undefined,
		},
		approachList:[
//			{
//				itemId:'1',
//				val:'ceshi',
//				marker:undefined,
//			},
		]
	}
	
	
	focusInpType:any='';//区分点击起点,重点,经过点的输入框
	drawTrackDatas=[];//画轨迹的数据
	samplingPoint={		//抽取途径时用的数据,轨迹数据开始截取sIndex ,截取结束eIndex;runList过滤画轨迹的数据数据中静止的点 listArr最终抽取的途径点
		sIndex:0,
		eIndex:0,
		runList:[],
		listArr:[]
	}
	
	
	
	myMap:any='';
	mapSize:any='';
    roadListArr=[];//所有轨迹数据
    deviceId='';
    
    lookLine:any;
    startMarker:any;
    endMarker:any; //点击查看轨迹时的轨迹路线,起点，终点
    selectItemId:any;//复选框选中路线的id;
    roadLength=0;//路线轨迹总条数
    totalDistance=0;//路线轨迹总路程
   
   	polylineObj = []; //对应的ltem的轨迹
	labelObj = []; //对应的ltem的轨迹的终点label
	
   	isUplodTrack=false;//监听上传轨迹模块是否打开
   	fileToUpload: File = null;//上传路线轨迹的文件
   	roadName='';//上传的路线名
   	remark='';//上传的描述
   	
   	isloading=true;//判断数据是否除以加载中
	isRemove=false;
   	getPointStatus=false;
   	infoWindow;
   	truckDriving;//轨迹规划实列对象
   	planningTrack;//轨迹规划路线
   	approachArr=[];//途径点list
   	planningPoints=[];//轨迹规划路线的所有经纬度点
   	singIndex:any;//当前操作的第几个途径点的
   	planningsignMarkers={  //记录轨迹规划时添加的起始,途径点的标记marker
   		sMarker:undefined,
   		eMarker:undefined,
   		approach:[],
   	}
   	selectFileStr='未选择文件';
   	searchTrackVal='';//轨迹搜索值
	constructor(private router: Router, private activatedRoute: ActivatedRoute, private jsonApiService: JsonApiService, private notificationService: NotificationService){} 
	// 接收子组件传递过来的数据 
	getSelectCarInfo(val){
		this.htmlParams.deviceId=val.deviceId;
		this.htmlParams.carNumber=val.carNumber;
//		this.selectedCompanyId=val.companyId;
//		this.selectedCompanyName=val.companyName;
	}
	getSelectTime(time){
		this.htmlParams.startTime=time.startTime;
		this.htmlParams.endTime=time.endTime;
	}
	getFocusInpType(type){
		this.focusInpType=type;
	}
	//添加途径点
	addApproachPoint(){
		let sortIndex=this.planningMarker.approachList.length>0?+this.planningMarker.approachList[this.planningMarker.approachList.length-1].itemId+1:1;
		let itemApproach={
				itemId:sortIndex,
				val:'', 
				marker:undefined,
			};
		this.planningMarker.approachList.push(itemApproach);
		this.focusInpType=sortIndex;
	}
	//删除途径点
	delApproachPoint(approachId){
		let len=this.planningMarker.approachList.length;
		for (let i=0;i<len;i++){
			let item =this.planningMarker.approachList[i];
			if(item.itemId==approachId){
				if(item.marker){
					this.myMap.remove(item.marker);
				}
				this.planningMarker.approachList.splice(i,1);
				break;
			}
		}
		this.focusInpType='';
	}
	//清空途径点
	removeApproachPoint(){
		this.focusInpType='';
		let len=this.planningMarker.approachList.length;
		for (let i=0;i<len;i++){
			let item =this.planningMarker.approachList[i];
			if(item.marker){
				this.myMap.remove(item.marker);
			}
		}
		this.planningMarker.approachList=[];
		this.closeRoutePlanning();
		if(this.planningMarker.starPoint.marker) this.myMap.remove(this.planningMarker.starPoint.marker);
		if(this.planningMarker.endPoint.marker) this.myMap.remove(this.planningMarker.endPoint.marker);
	}
	
	//获取抽样数据中的在行使数据,过滤静止的数据
	getSamplingApproach(){
		if(this.samplingPoint.sIndex<1&&this.samplingPoint.eIndex<1){
			return;
		}
		let len3=this.planningMarker.approachList.length;
		if(len3>0){
			for(let i=0;i<len3;i++){
				let marker=this.planningMarker.approachList[i].marker;
				if(marker){
        			this.myMap.remove(marker);
        		}
			}
		}
		this.planningMarker.approachList=[];
		let _listArr=this.drawTrackDatas.slice(this.samplingPoint.sIndex,this.samplingPoint.eIndex);//根据发车时间-卸货前停止区间截取数据后过滤掉静止的数据


		let len5=_listArr.length;
		let allDistance=0;
		for(let i=0;i<len5-1;i++){
			allDistance=allDistance+common.caculationDistance(_listArr[i],_listArr[i+1]);
		}
		if(allDistance<2000){
			this.jsonApiService.message('总路程小于2公里,不进行抽取途经点');
			return;
		}
		let eqdis=Math.floor(allDistance/9);
		var _distace=0;//区间距离
		this.planningMarker.approachList=[];
		for(let i=0;i<len5-1;i++){
			let _itme=_listArr[i];
			_distace=_distace+common.caculationDistance(_itme,_listArr[i+1]);
			if(_distace>=eqdis){
				_distace=0;
				this.addApproachPoint();
				let _lens=this.planningMarker.approachList.length;
				this.planningMarker.approachList[_lens-1].val=_itme.x+','+_itme.y;
				this.planningMarkerAdd(_itme.lnglat.lng,_itme.lnglat.lat);
			}
		}
	}
	
	getStartLnglat(){
		let sLngTime=this.htmlParams.runTime;//起点坐标的时间
		let len=this.drawTrackDatas.length;
		if(len<0){
			this.jsonApiService.message('轨迹数据为空');
			return;
		}
		for(let i=0;i<len;i++){
			let item=this.drawTrackDatas[i];
			let time1=new Date(item.uploadDate.replace(/-/g,"/")).getTime();
			let time2=new Date(sLngTime.replace(/-/g,"/")).getTime();
			if(time1-time2>=0){
				this.samplingPoint.sIndex=i;
				this.focusInpType='starPoint';
				this.planningMarker.starPoint.val=item.x+','+item.y;
				this.planningMarkerAdd(item.lnglat.lng,item.lnglat.lat);
				if(this.planningMarker.starPoint.val&&this.planningMarker.endPoint.val){
					this.getSamplingApproach();
				}
				break;
			}
		}
		
		
		
	}
	getEndLnglat(){
		let eLngTime=this.htmlParams.stopBefore;//终点坐标的时间
		let len=this.drawTrackDatas.length;
		if(len<0){
			this.jsonApiService.message('轨迹数据为空');
			return;
		}
		for(let i=0;i<len;i++){
			let item=this.drawTrackDatas[i];
			let time1=new Date(item.uploadDate.replace(/-/g,"/")).getTime();
			let time2=new Date(eLngTime.replace(/-/g,"/")).getTime();
			if(time1-time2>=0||i==len-1){
//				if(i==len-1){
//					this.jsonApiService.message('取最后一个时间点');
//				}
				this.samplingPoint.eIndex=i;
				this.focusInpType='endPoint';
				this.planningMarker.endPoint.val=item.x+','+item.y;
				this.planningMarkerAdd(item.lnglat.lng,item.lnglat.lat);
				if(this.planningMarker.starPoint.val&&this.planningMarker.endPoint.val){
					this.getSamplingApproach();
				}
				break;
			}
		}
		
	}
	
	changeAmapPointType(str){
		var result;
		var lnglat=str.split(',');
		if(lnglat.length==2){
			var point=toAMapPoint(lnglat[0],lnglat[1]);
			if(point){
				result=point;
			}
     	}
		return result;
	}
	
	closeRoutePlanning(){
		if(!this.truckDriving) return;
		if(this.planningMarker.starPoint.marker) this.myMap.add(this.planningMarker.starPoint.marker);
		if(this.planningMarker.endPoint.marker) this.myMap.add(this.planningMarker.endPoint.marker);
		for(let item of this.planningMarker.approachList){
			if(item.marker){
				this.myMap.add(item.marker);
			}
			
		}
		this.truckDriving.clear();
	}
	routePlanning(){
		
		var sMarPoint=this.planningMarker.starPoint.val;
     	var eMarPoint=this.planningMarker.endPoint.val;
     	if(!eMarPoint||!eMarPoint) {
     		this.jsonApiService.message('起始结束坐标不能为空');
     		return;
     	}
        if(this.planningMarker.starPoint.marker){
    		this.myMap.remove(this.planningMarker.starPoint.marker);
    	}
		if(this.planningMarker.endPoint.marker){
    		this.myMap.remove(this.planningMarker.endPoint.marker);
    	}
		let len=this.planningMarker.approachList.length;
		if(len>0){
			for(let i=0;i<len;i++){
				let marker=this.planningMarker.approachList[i].marker;
				if(marker){
        			this.myMap.remove(marker);
        		}
			}
		}
		var sLnglat=this.changeAmapPointType(sMarPoint);
		var eLnglat=this.changeAmapPointType(eMarPoint);
     	if(!sLnglat||!eLnglat){
     		this.jsonApiService.message('起始结束坐标转换失败');
     		return;
     	}
		this.planningPoints = [];
		if(this.planningTrack) this.myMap.remove(this.planningTrack);
		if(!this.truckDriving){
			this.truckDriving = new AMap.TruckDriving({
				map: this.myMap,
				policy: 0, // 规划策略
				size: 1, // 车型大小
				width: 2.5, // 宽度
				height: 2, // 高度      
				load: 1, // 载重
				weight: 12, // 自重
				axlesNum: 2, // 轴数
				province: '京', // 车辆牌照省份
				isOutline: true,
				outlineColor: '#ffeeee'
			})
		}
		var path = [];
		path.push({lnglat:[sLnglat.lng,sLnglat.lat]});//起点
		
		for(let i=0;i<len;i++){
			let val=this.planningMarker.approachList[i].val;//每一个途径点的经纬度坐标;
			let _point=this.changeAmapPointType(val);
			if(_point) path.push({lnglat:[_point.lng,_point.lat]});//途径点
		}
		
		path.push({lnglat:[eLnglat.lng,eLnglat.lat]});//终点
		var that = this;
		this.truckDriving.search(path, function(status, result) {
			// searchResult即是对应的驾车导航信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
			if (status === 'complete') {
				var routes = result.routes;
				var points = [];
				routes.forEach(item=>{
					var steps = item.steps;
					steps.forEach(st=>{
						points.push(st.path);
					})
				})
				points.forEach(item2=>{
					item2.forEach(p =>{
						let aMapPoint=AMapToWgs4(p.lng,p.lat);
						if(aMapPoint) that.planningPoints.push(aMapPoint);
					})
				})
			} else {
				that.jsonApiService.message('获取货车规划数据失败')
			}
		})
		
		
	}
	//点击查看轨迹
	lookTrack(){
		this.removeApproachPoint();
		
		if(this.lookLine) {
			this.myMap.remove(this.lookLine);
		}
		if(this.startMarker){
			this.myMap.remove(this.startMarker);
		}
		if(this.endMarker){
			this.myMap.remove(this.endMarker);
		}
		if(this.infoWindow)this.infoWindow.close();
		let deviceId = this.htmlParams.deviceId;
		let startTime = $("#datetimepicker1").val();
		let endTime = $("#datetimepicker2").val();
//		let deviceId = '431453255';
//		let startTime = '2019-04-03 15:39:45';
//		let endTime = '2019-04-04 15:39:45';
		if(deviceId==''){
			this.jsonApiService.message('设备ID不能为空');
			return;
		}
		layer.load();
		let reqdata='deviceId='+deviceId+'&startTime='+startTime+'&endTime='+endTime;
		this.jsonApiService.http('track/localtrack.html',reqdata).subscribe(result=>{
			layer.closeAll('loading');
			if(result.data.length<2){
				this.jsonApiService.message('该时间段没有数据');
				return;
			}
			let paramArr = [];
			//转换成高德地图坐标系   国测坐标系
			result.data.forEach(item=>{
				if(item.x == '0'||item.y == '0'){return true;}
				let _p=toAMapPoint(item.x,item.y);
				if(_p){
					item.lng=_p.lng;
					item.lat=_p.lat;
					item.lnglat=new AMap.LngLat(item.lng,item.lat);
					paramArr.push(item);
				}
			})
			this.drawTrackDatas=paramArr;
			if(paramArr.length > 0){
				this.drawTrackLine(paramArr,false);
				this.myMap.setZoomAndCenter(12,[paramArr[0].lng, paramArr[0].lat]);
			}else{
				this.jsonApiService.message('该时间段没有轨迹');
			}
		})
	}
	//画查看轨迹的路线
	drawTrackLine(paramArr,paramColor) {
		let lineArr = [];
		for(let i = 0; i < paramArr.length; i++) {
			let p = new AMap.LngLat(paramArr[i].lng, paramArr[i].lat);
			lineArr.push(p)
		}
		
		let color = "blue";
		if(paramColor) {
			color = paramColor;
		}
		let polyline = new AMap.Polyline({
			path: lineArr,
			strokeColor: color,
			strokeWeight: 6,
			strokeOpacity: 0.5
		}); //创建路线
		this.lookLine = polyline;
	    var startIcon = new AMap.Icon({
	        size: new AMap.Size(20, 50),
	        image: 'assets/img/trackImage/startMarker.png',
//	        imageSize: new AMap.Size(20, 50),
//	        imageOffset: new AMap.Pixel(-9, -3)
	    });
		var endIcon = new AMap.Icon({
	        size: new AMap.Size(20, 50),
	        image: 'assets/img/trackImage/endMarker.png',
	    });
	    this.startMarker = new AMap.Marker({
	        position: new AMap.LngLat(paramArr[0].lng,paramArr[0].lat),
	        icon: startIcon,
//	        offset: new AMap.Pixel(-13, -30)
	    });
	  	this.endMarker = new AMap.Marker({
	        position: new AMap.LngLat(paramArr[paramArr.length-1].lng,paramArr[paramArr.length-1].lat),
	        icon: endIcon,
	    });
		this.myMap.add([this.startMarker,this.endMarker,this.lookLine]);
		//轨迹点击事件
//		var style = [{
//	        url: 'https://a.amap.com/jsapi_demos/static/images/mass0.png',
//	        anchor: new AMap.Pixel(6, 6),
//	        size: new AMap.Size(11, 11)
//	    }];
//		var mass = new AMap.MassMarks(paramArr, {
//	        opacity: 0,
//	        zIndex: 111,
//	        cursor: 'pointer',
//       	style: style
//	    });
//   	mass.setMap(this.myMap);
//   	mass.on('click', function (e) {
//	       this.createTextInfo(e);
//	    }.bind(this));
	}
	//创建textInfo信息窗口
	createTextInfo(obj){
		let content = '<div class="">'+
		'<ul>'+
		'<li><span class="leftSpan">载重量：</span><span class="rightSpan">'+ obj.data.weight +'（吨）</span></li>'+	
		'<li><span class="leftSpan">速度：</span><span class="rightSpan">'+ obj.data.speed +' KM/H</span></li>'+	
		'<li><span class="leftSpan">经度：</span><span class="rightSpan">'+ obj.data.lng +'</span></li>'+
		'<li><span class="leftSpan">纬度：</span><span class="rightSpan">'+ obj.data.lat +'</span></li>'+
		'<li><span class="leftSpan">时间：</span><span class="rightSpan">'+obj.data.uploadDate+'</span></li>'+
		'</ul>'+
		'</div>';
		this.infoWindow =  new AMap.InfoWindow({content:content});
		this.infoWindow.open(this.myMap,new AMap.LngLat(obj.data.lng,obj.data.lat)); //开启信息窗口
	}
	//单一条轨迹路线的点击事件
	//绘画选定轨迹item路线
	//地图拾取经纬度点(marker)
	planningMarkerAdd(lng,lat){
	    let markerContent = '<img src="assets/img/trackImage/midA.png">'+
	    '<span class="approachIndex" style="position: absolute;color:#ffffff;right:0px;width:18px;text-align:center;font-weight:bold">'+this.focusInpType+'</span>';
        let markerType=$('.getMapPoint').attr('name');
        let position = new AMap.LngLat(lng,lat);
        
        
        if(this.focusInpType=='starPoint'){
        	markerContent = '<img src="assets/img/trackImage/startA.png">';
        	if(this.planningMarker.starPoint.marker){
        		this.myMap.remove(this.planningMarker.starPoint.marker);
        	}
			this.planningMarker.starPoint.marker= new AMap.Marker({
		        position: position,
		        content: markerContent,
		        offset: new AMap.Pixel(-13, -30),
		        draggable: true
		    });
		    this.myMap.add(this.planningMarker.starPoint.marker);
		    this.planningMarker.starPoint.marker.on('dragend',function(e){
		    	
		    	let wgsPoint=AMapToWgs4(e.lnglat.lng,e.lnglat.lat);
				if(wgsPoint){
					this.planningMarker.starPoint.val=wgsPoint.lng + "," + wgsPoint.lat;
					this.focusInpType='starPoint';
				}
		    }.bind(this))
		}
		else if(this.focusInpType=='endPoint'){
			markerContent = '<img src="assets/img/trackImage/endA.png">';
			if(this.planningMarker.endPoint.marker){
        		this.myMap.remove(this.planningMarker.endPoint.marker);
        	}
			this.planningMarker.endPoint.marker= new AMap.Marker({
		        position: position,
		        content: markerContent,
		        offset: new AMap.Pixel(-13, -30),
	          	draggable: true
		    });
		    this.planningMarker.endPoint.marker.on('dragend',function(e){
		    	let wgsPoint=AMapToWgs4(e.lnglat.lng,e.lnglat.lat);
				if(wgsPoint){
					this.planningMarker.endPoint.val=wgsPoint.lng + "," + wgsPoint.lat;
					this.focusInpType='endPoint';
				}
		    }.bind(this))
		    this.myMap.add(this.planningMarker.endPoint.marker);
		}
		else{
			let len=this.planningMarker.approachList.length;
			for(let i=0;i<len;i++){
				let item=this.planningMarker.approachList[i];
				if(this.focusInpType==item.itemId){
					if(item.marker){
	        			this.myMap.remove(item.marker);
	        		}
					item.marker=new AMap.Marker({
				        position: position,
				        content: markerContent,
				        offset: new AMap.Pixel(-13, -30),
				        draggable: true
				    });
				    item.marker.on('dragend',function(e){
				    	var wgsPoint=AMapToWgs4(e.lnglat.lng,e.lnglat.lat);
						if(wgsPoint){
							item.val=wgsPoint.lng + "," + wgsPoint.lat;
							this.focusInpType=item.itemId;
						}
				    }.bind(this))
				   	this.myMap.add(item.marker);
					break;
				}
			}
		}
	}
	
	//地图点击获取起始点坐标位置
	getPointEvent() {
		var that=this;
		this.myMap.on('click',function(e) {
			if(!that.focusInpType) return;
			that.planningMarkerAdd(e.lnglat.lng,e.lnglat.lat);
			var wgsPoint=AMapToWgs4(e.lnglat.lng,e.lnglat.lat);
			if(wgsPoint){
				let pointString=wgsPoint.lng + "," + wgsPoint.lat;
				if(that.focusInpType=='starPoint'){
					that.planningMarker.starPoint.val=pointString;
				}
				else if(that.focusInpType=='endPoint'){
					that.planningMarker.endPoint.val=pointString;
				}
				else{
					let len=that.planningMarker.approachList.length;
					for(let i=0;i<len;i++){
						let item=that.planningMarker.approachList[i];
						if(that.focusInpType==item.itemId){
							item.val=pointString;
						}
					}
				}
			}
		});
	}
	//点击修复轨迹获取所选参数
	getRodioTrack() {
		var that=this;
		let postData:any = {
			deviceId:this.htmlParams.deviceId,
			startLng:'',
			startLat:'',
			endLng:'',
			endLat:'',
			runBefore:this.htmlParams.runBefore,
			runTime:this.htmlParams.runTime,
			stopBefore:this.htmlParams.stopBefore,
			stopTime:this.htmlParams.stopTime,
			isRemove:this.htmlParams.isRemove,
			isMakeup:this.htmlParams.isMakeup,
			pointArr:'',
			
		};
		
		if(this.planningMarker.starPoint.val !== '') {
			postData.startLng = this.planningMarker.starPoint.val.split(',')[0];
			postData.startLat = this.planningMarker.starPoint.val.split(',')[1];
			if(!postData.startLng || !postData.startLat) {
				this.jsonApiService.message('请检查坐标格式是否正确');
				return;
			}
		}
		if(this.planningMarker.endPoint.val !== '') {
			postData.endLng = this.planningMarker.endPoint.val.split(',')[0];
			postData.endLat = this.planningMarker.endPoint.val.split(',')[1];
			if(!postData.endLng || !postData.endLat) {
				this.jsonApiService.message('请检查坐标格式是否正确');
				return;
			}
		}
		let timeType1=common.checkDateFormat(postData.runBefore);
		let timeType2=common.checkDateFormat(postData.runTime);
		let timeType3=common.checkDateFormat(postData.stopBefore);
		let timeType4=common.checkDateFormat(postData.stopTime);
		if(!timeType1||!timeType2||!timeType3||!timeType4){
			this.jsonApiService.message('请检查输入的时间格式是否正确');
			return;
		}
		if(this.selectItemId){
			let reqdata='trackId='+this.selectItemId;
			this.jsonApiService.http("track/getroad.html", reqdata).subscribe(result => {
				let pArr=[];
				for(let item of result.data.pointList){
					pArr.push({lng:item.lng,lat:item.lat})
				}
				postData.pointArr=JSON.stringify(pArr);
				layer.load();
				$.ajax({
					type: 'POST',
					url : config.BaseURL+"trackV2/autoretifytrack.html",
			        xhrFields: {
						withCredentials: true
					},
					data: postData,
					dataType: "json",
					success: function(result) {
						layer.closeAll('loading');
						that.jsonApiService.message(result.message);
					},
					error: function() {
						layer.closeAll('loading');
						that.jsonApiService.message('网络错误，请联系管理员');
					}
				})
				
			})
		}else{
			if(this.planningPoints.length<2){
				this.jsonApiService.message('请进行路线规划');
				return;
			}
			postData.pointArr=JSON.stringify(this.planningPoints);
			layer.load();
			$.ajax({
				type: 'POST',
				url : config.BaseURL+"trackV2/autoretifytrack.html",
		        xhrFields: {
					withCredentials: true
				},
				data: postData,
				dataType: "json",
				success: function(result) {
					layer.closeAll('loading');
					that.jsonApiService.message(result.message);
				},
				error: function() {
					layer.closeAll('loading');
					that.jsonApiService.message('网络错误，请联系管理员');
				}
			})
		}
		
		
	}
	/**点击撤销轨迹获取所选参数*/
	revokeTrack() {
		if(this.htmlParams.deviceId == '') {
			this.jsonApiService.message('请输入设备编号');
			return;
		}
		let startTime = $("#datetimepicker1").val();
		let endTime = $("#datetimepicker2").val();
		let reqdata='deviceId='+this.htmlParams.deviceId+'&startTime='+startTime+'&endTime='+endTime+'&isRemove='+this.htmlParams.isRemove;
		this.jsonApiService.http("track/canceltrack.html", reqdata).subscribe(result => {
			this.jsonApiService.message(result.message);
		})
	}
  	isTimeFormat(value){
  		let isTime=common.checkDateFormat(value);
  		if(!isTime){
  			this.jsonApiService.message('输入的时间格式不正确,例:2018-08-01 00:00:00');
  		}
  	}
  	ngOnInit() {
  		this.initListData();
		this.initMap();
//		this.listItemEvent();
		this.getPointEvent();
		$(document).keyup(function(event){
			var isFocus=$("#searchTrackInp").is(":focus"); 
			if(isFocus){
				if(event.keyCode ==13){
					this.searchTrackList();
				}
			}
		}.bind(this));
  	}
  	//单一条轨迹路线的点击事件
	listItemEvent(e,sortItem){
		let that=this;
		let isSelect = $(e.target).attr('class').split(' ')[1];
		if(!isSelect) {
			$(e.target).addClass('selectItem');
			that.drawItemLine(sortItem);
		} else {
			$(e.target).removeClass('selectItem');
			that.myMap.remove(that.polylineObj[sortItem - 1]);
			that.myMap.remove(that.labelObj[sortItem - 1]);
			that.polylineObj[sortItem - 1] = '0';
			that.labelObj[sortItem - 1] = '0';
		}
	}
	//绘画选定轨迹item路线
	drawItemLine(sortItem) {
		let trackId=this.roadListArr[sortItem - 1].id;
		if(!trackId){
			this.jsonApiService.message('未获取到轨迹id');
			return;
		}
		let reqdata='trackId='+trackId;
		this.jsonApiService.http("track/getroad.html", reqdata).subscribe(result => {
			let darw=toAMapPointArr(result.data.pointList);//转成百度坐标系
			if(darw.length<2){
				this.jsonApiService.message('该路线没有数据');
				return;
			}
			let lineArr = [];
			for(var i = 0; i < darw.length; i++) {
				var p = new AMap.LngLat(darw[i].lng,darw[i].lat);
				lineArr.push(p)
			}
			let color = "blue";
			if(sortItem % 3 == 2) {
				color = "red"
			}
			if(sortItem % 3 == 1) {
				color = "#d15b47"
			}
			if(sortItem % 3 == 0) {
				color = "black"
			}
			
			let polyline = new AMap.Polyline({
				path:lineArr,
				strokeColor: color,
				strokeWeight: 6,
				strokeOpacity: 0.6
			}); //创建路线
			this.myMap.add(polyline);
			this.polylineObj[sortItem - 1] = polyline
			let point = new AMap.LngLat(darw[darw.length-1].lng,darw[darw.length-1].lat);
			let opts = {
		  		position : point,    // 文本标注位置
		  		offset   : new AMap.Size(0, 0)    //文本偏移量
			}
			let label = new AMap.Text({ 
				text:'终点',
	        	anchor:'center', // 设置文本标记锚点
	        	draggable:false,
	        	cursor:'pointer',
	        	style:{
	            	'color': color
	        	},
	    	  position: [darw[darw.length-1].lng,darw[darw.length-1].lat]
			});  // 创建文本标注对象
			label.setMap(this.myMap);
			this.labelObj[sortItem - 1] = label;
		})
	}
  	ngOnDestroy(){
		document.onclick = null;
		$(document).unbind('keyup'); //移除键盘回车事件
	}
  	addressSearch:any = '';		//地址快捷搜索
  	initMap(){
  			
  		this.myMap= new AMap.Map("myMap", {
  			resizeEnable: true,
//			zoom: 14,
//			center: [121.498586, 31.239637]
		});
	    this.myMap.getCity( function(info){});
		
		//输入提示
		var autoOptions = {
			input: "addressSearch"
		};
		var auto = new AMap.Autocomplete(autoOptions);
		var placeSearch = new AMap.PlaceSearch({
			map: this.myMap
		});  //构造地点查询类
		//注册监听，当选中某条记录时会触发
		AMap.event.addListener(auto, "select", e=>{
			placeSearch.setCity(e.poi.adcode);
			placeSearch.search(e.poi.name);  //关键字查询查询
		});
		this.myMap.setZoom(12);
  	}
  	//初始化轨迹list
	initListData(){
		this.isloading=true;
		this.jsonApiService.http("track/getallroad.html", '').subscribe(result => {
			this.isloading=false;
			this.roadListArr=result.data;
			let len=result.data.length;
			let allDistance=0;
			for(let i=0;i<len;i++){
				let distance=parseInt(result.data[i].distance)/1000;
				allDistance=allDistance+distance;
				result.data[i].distance=Math.floor(distance*100)/100;//距离m转换km,保留小数后2位
				this.polylineObj[i] = '0';
				this.labelObj[i]='0';
			}
			this.roadLength=len;
			this.totalDistance=Math.floor(allDistance*100)/100;
		})
	}
	//右侧轨迹搜索
	searchTrackList(){
		$('.searchPosition').removeClass('searchPosition');
		let queryString=common.stringTrim(this.searchTrackVal);
		if(queryString==''){
			return;
		}
		var findCount=0;
		let container=$('.trackList');
		$('.liItem').each(function(index,obj){
			let  valStar=common.stringTrim($(this).text());
			if(valStar!==''&&valStar.match(queryString+".*")){
				if(findCount<1){
					let top=$(this).offset().top-container.offset().top + container.scrollTop();
					container.animate({scrollTop: top});
				}
				findCount=findCount+1;
				$(this).addClass('searchPosition');
			}
		})
		let messtring='查询出'+findCount+'条轨迹';
		if(findCount>1) messtring+='定位到查询出的第一条';
		this.jsonApiService.message(messtring);
	}
	
	//打开或关闭上传轨迹模块
	isOpenUplod(status){
		if(status=='open'){
			this.isUplodTrack=true;
		}
		else{
			this.isUplodTrack=false;
			
		}
	}
	//获取需要上传的文件
	getFile(files: FileList) {
		this.fileToUpload = files.item(0);
		
		if(!this.fileToUpload){
			this.selectFileStr='未选择文件';
//			this.jsonApiService.message('请选择文件')
			return false;
		}
		this.selectFileStr=this.fileToUpload.name;
   }
	//checkInput 选中一条轨迹路线
	selectItem(e,id){
		e.stopPropagation();
		if(this.selectItemId==id){
			this.selectItemId='';
		}else{
			
			this.selectItemId=id;
		}
	}
	//提交上传的轨迹
	submitUpload(){
		if(this.roadName==''){
			this.jsonApiService.message('请输入上传的轨迹名称');
        	return false;
		}
		if(this.remark==''){
			this.jsonApiService.message('请输入上传的轨迹描述');
        	return false;
		}
		if(!this.fileToUpload){
     		this.jsonApiService.message('请选择需要上传的文件');
        	return false;
       }
		let reqdata = new FormData();
        reqdata.append('roadName', this.roadName);
        reqdata.append('remark', this.remark);
        reqdata.append('file', this.fileToUpload);
		this.jsonApiService.form_http("track/uploadroadfile.html", reqdata).subscribe(result => {
			this.jsonApiService.message(result.message);
			if(!result.success){
				return;
			}
			this.isUplodTrack=false;
			this.roadName='';
			this.remark='';
			let len=this.polylineObj.length;
			for(let i=0;i<len;i++){
				this.myMap.remove(this.polylineObj[i]);
				this.myMap.remove(this.labelObj[i]);
			}
			this.initListData();
		})
	}
	//删除路线轨迹
	delTrack(){
		if(!this.selectItemId){
			this.jsonApiService.message('请选择需要删除的轨迹路线');
			return;
		}
		this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(()=>{
			let reqdata='id='+this.selectItemId;
			this.jsonApiService.http('track/deleteroad.html',reqdata).subscribe(result=>{
				this.jsonApiService.message(result.message);
				let len=this.roadListArr.length
				for (let i=0;i<len;i++){
					let id=this.roadListArr[i].id;
					if(id==this.selectItemId){
						
						if(this.polylineObj[i]!=='0'){
							this.myMap.remove(this.polylineObj[i]);
							this.myMap.remove(this.labelObj[i]);
						}
						this.roadListArr.splice(i,1);
						this.polylineObj.splice(i,1);
						this.labelObj.splice(i,1);
						break;
					}
				}
			})
		})
	}
}